<?php
!function_exists('readover') && exit('Forbidden');

function writenewmsg($msg,$sysmsg=0) {
	@extract($GLOBALS, EXTR_SKIP);
	include(GetLang('writemsg'));
	$lang[$msg[2]] && $msg[2] = Char_cv($lang[$msg[2]]);
	$lang[$msg[4]] && $msg[4] = Char_cv($lang[$msg[4]]);
	$msg[0] = addslashes($msg[0]);
	$msg[6] = Char_cv($msg[6]);
	!$msg[6] && $msg[6]='SYSTEM';

	$rt = $db->get_one("SELECT uid,username,newpm FROM pw_members WHERE username='$msg[0]'");
	Add_S($rt);
	if ($msg[5] == 'Y') {
		$rs = $db->get_one("SELECT COUNT(*) AS sum FROM pw_msg WHERE type='sebox' AND fromuid='$msg[1]'");
		$rs['sum'] >= $gp_maxmsg && Showmsg('sebox_full');
		$db->update("INSERT INTO pw_msg(touid,fromuid,username,type,ifnew,mdate) VALUES('$rt[uid]','$msg[1]','$rt[username]','sebox','0','$msg[3]')");
		$mid = $db->insert_id();
		$db->update("REPLACE INTO pw_msgc(mid,title,content) VALUES ('$mid','$msg[2]','$msg[4]')");
	}
	$db->update("INSERT INTO pw_msg(touid,fromuid,username,type,ifnew,mdate) VALUES('$rt[uid]','$msg[1]','$msg[6]','rebox','1','$msg[3]')");
	$mid = $db->insert_id();
	$db->update("REPLACE INTO pw_msgc(mid,title,content) VALUES ('$mid','$msg[2]','$msg[4]')");
	
	if ($rt['newpm'] == 0) {
		$db->update("UPDATE pw_members SET newpm='1' WHERE uid='$rt[uid]'");
	}
}

function delete_msgc($ids = null) {
	$GLOBALS['db']->update("DELETE mc FROM pw_msgc mc LEFT JOIN pw_msg m ON mc.mid=m.mid LEFT JOIN pw_msglog ml ON mc.mid=ml.mid WHERE m.mid is NULL AND ml.mid is NULL".($ids ? " AND mc.mid IN($ids)" : ''));
}

function send_msgc($msg) {
	global $db;
	if (!is_array($msg)) return;

	$uid = $sql = $mc_sql = '';
	foreach ($msg as $k => $v) {
		if (is_array($v)) {
			$sql .= ($sql ? ',' : '')."('$v[0]','$v[1]','$v[2]','$v[3]','$v[4]','$v[5]')";
			$uid .= ($uid ? "','" : '').$v[0];
		}
	}
	if ($sql) {
		$db->update("INSERT INTO pw_msg(touid,fromuid,username,type,ifnew,mdate) VALUES $sql");
		$mid = $db->insert_id();
		foreach ($msg as $k => $v) {
			if (is_array($v)) {
				$mc_sql .= ($mc_sql ? ',' : '')."('".($mid++)."','$v[6]','$v[7]')";
			}
		}
		if ($mc_sql) {
			$db->update("REPLACE INTO pw_msgc(mid,title,content) VALUES $mc_sql");
		}
		$db->update("UPDATE pw_members SET newpm=1 WHERE uid IN('$uid')");
	}
}
?>